using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Matrix.Notification.Options;

namespace Matrix.Notification.Channels
{
    /// <summary>
    /// 短信通知通道实现
    /// </summary>
    public class SmsNotificationChannel : INotificationChannel
    {
        public string ChannelType => "Sms";

        private readonly ILogger<SmsNotificationChannel> _logger;
        private readonly SmsChannelOptions _options;

        public SmsNotificationChannel(
            ILogger<SmsNotificationChannel> logger,
            IOptions<NotificationOptions> options)
        {
            _logger = logger;
            ArgumentNullException.ThrowIfNull(options);

            // 从Dictionary配置中构建SmsChannelOptions
            var smsConfig = options.Value?.Sms ?? new Dictionary<string, object>();
            _options = new SmsChannelOptions();

            if (smsConfig.TryGetValue("IsEnabled", out var isEnabled))
                _options.IsEnabled = Convert.ToBoolean(isEnabled);

            if (smsConfig.TryGetValue("Provider", out var provider))
                _options.Provider = Convert.ToString(provider) ?? string.Empty;

            if (smsConfig.TryGetValue("AccessKey", out var accessKey))
                _options.AccessKey = Convert.ToString(accessKey) ?? string.Empty;

            if (smsConfig.TryGetValue("SecretKey", out var secretKey))
                _options.SecretKey = Convert.ToString(secretKey) ?? string.Empty;

            if (smsConfig.TryGetValue("SignName", out var signName))
                _options.SignName = Convert.ToString(signName) ?? string.Empty;

            if (smsConfig.TryGetValue("TemplateCode", out var templateCode))
                _options.TemplateCode = Convert.ToString(templateCode) ?? string.Empty;
        }

        public Task<bool> IsAvailableAsync(CancellationToken cancellationToken = default)
        {
            return Task.FromResult(_options.IsEnabled &&
                                   !string.IsNullOrEmpty(_options.Provider) &&
                                   !string.IsNullOrEmpty(_options.AccessKey) &&
                                   !string.IsNullOrEmpty(_options.SecretKey));
        }

        public async Task<NotificationChannelResult> SendAsync(
            object notification,
            CancellationToken cancellationToken = default)
        {
            try
            {
                var smsNotification = notification as SmsNotification;
                if (smsNotification == null)
                {
                    _logger.LogError("通知对象不是短信类型");
                    return CreateFailureResult("通知对象不是短信类型");
                }

                _logger.LogInformation("开始发送短信通知: {PhoneNumber} - {Content}",
                    smsNotification.PhoneNumber, smsNotification.Content);

                // 简化实现：记录短信信息但不实际发送（需要配置短信服务商）
                _logger.LogInformation("短信发送模拟成功: {PhoneNumber} - {Content}",
                    smsNotification.PhoneNumber, smsNotification.Content);

                return new NotificationChannelResult
                {
                    IsSuccess = true,
                    SuccessCount = 1,
                    FailureCount = 0,
                    SentAt = DateTime.UtcNow,
                    MessageId = Guid.NewGuid().ToString()
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "短信发送失败: {Error}", ex.Message);
                return CreateFailureResult(ex.Message);
            }
        }

        public async Task<NotificationChannelResult> SendBatchAsync(
            System.Collections.Generic.IReadOnlyCollection<object> notifications,
            CancellationToken cancellationToken = default)
        {
            var result = new NotificationChannelResult();

            foreach (var notification in notifications)
            {
                var sendResult = await SendAsync(notification, cancellationToken);
                if (sendResult.IsSuccess)
                {
                    result.SuccessCount++;
                }
                else
                {
                    result.FailureCount++;
                    result.ErrorMessage = sendResult.ErrorMessage;
                }
            }

            result.IsSuccess = result.FailureCount == 0;
            result.SentAt = DateTime.UtcNow;

            return result;
        }

        private static NotificationChannelResult CreateFailureResult(string errorMessage)
        {
            return new NotificationChannelResult
            {
                IsSuccess = false,
                ErrorMessage = errorMessage,
                SuccessCount = 0,
                FailureCount = 1,
                SentAt = DateTime.UtcNow
            };
        }
    }

    /// <summary>
    /// 短信通知数据
    /// </summary>
    public class SmsNotification
    {
        /// <summary>
        /// 收件人手机号
        /// </summary>
        public string PhoneNumber { get; set; } = string.Empty;

        /// <summary>
        /// 短信内容
        /// </summary>
        public string Content { get; set; } = string.Empty;

        /// <summary>
        /// 模板代码（可选）
        /// </summary>
        public string? TemplateCode { get; set; }

        /// <summary>
        /// 模板参数（可选）
        /// </summary>
        public Dictionary<string, object>? TemplateParams { get; set; }
    }

    /// <summary>
    /// 短信通道配置选项
    /// </summary>
    public class SmsChannelOptions
    {
        /// <summary>
        /// 是否启用
        /// </summary>
        public bool IsEnabled { get; set; } = true;

        /// <summary>
        /// 短信服务商（Aliyun、Tencent等）
        /// </summary>
        public string Provider { get; set; } = string.Empty;

        /// <summary>
        /// AccessKey
        /// </summary>
        public string AccessKey { get; set; } = string.Empty;

        /// <summary>
        /// SecretKey
        /// </summary>
        public string SecretKey { get; set; } = string.Empty;

        /// <summary>
        /// 短信签名
        /// </summary>
        public string SignName { get; set; } = string.Empty;

        /// <summary>
        /// 默认模板代码
        /// </summary>
        public string TemplateCode { get; set; } = string.Empty;
    }
}